﻿using System;
using System.Threading.Tasks;
using Abp.Application.Services.Dto;
using HCD.User;
using HCD.User.Dtos;
using HCD.Web.Authorizer;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Partner.Utility;

namespace HCD.Web.Controllers.ApiControllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : EnterpriseControllerBase
    {
        public IUserAppService  UserApp {get;set;}
        /// <summary>
        ///  用户登录
        /// </summary>
        /// <param name="dto"></param>
        /// <returns>Data:JWTToken</returns>
        [AllowAnonymous, HttpPost]
        public async Task<BizResult<string>> Login([FromBody]LoginInput dto)
        {
            dto.IpAddress = dto.IpAddress?? GetUserIp(Request.HttpContext);
            var hash = Configuration["Customization:JwtKey"];
            dto.Password = EncryptUtil.AESEncrypt(dto.Password, hash);
            var userMini = await UserApp.Login(dto);
            var auth = new AuthModel { Id = userMini.Id, EmpNo = userMini.EmpNo, UserName = userMini.UserName, PhoneNumber = userMini.PhoneNumber, Name = userMini.Name, IsAdmin = false, Exp = DateTime.Now.AddDays(1), TenantID = null };
            var re = new BizResult<string> { Success = true, Data = JWTUtil.GenerateToken(auth) };
            return re;
        }

        /// <summary>
        /// 获取用户个人信息
        /// </summary>
        /// <returns>Data:个人信息</returns>
        [HttpGet]
        public async Task<BizResult<UserDto>> GetCurrentUser()
        {
            var UserDto = await UserApp.GetAsync(new EntityDto<long>{ Id = CurrentOperator.Id});
            if(UserDto!= null)
                return new BizResult<UserDto>() { Data = UserDto, Success = true };
            else
                throw new BizException(L("UserIsNotFound"));
        }
    }
}